package com.haodai.vip.tomcat.utils;


import com.haodai.vip.tomcat.server.Config;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

import java.io.*;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;

/**
 * Created by huangtao on 17/5/24.
 */
public class IOUtils {
    private static  int POSITION = 0;

    public static String requestHeaderString(InputStream inputStream){
        String requestHeaderString = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            boolean isEndWithN = false;
            boolean isContentStart = false;
            char c;
            while ((c = (char) inputStream.read()) != -1) {
                if (c == '\r') {
                    if (isEndWithN){
                        isContentStart = true;
                    }
                    continue;
                }

                if (c == '\n') {
                    if (isContentStart) {
                        break;
                    }
                    isEndWithN = true;
                } else {
                    isEndWithN = false;
                }
                bos.write(c);
            }
            requestHeaderString = new String(bos.toByteArray(), Config.Encoding.ENCODE);
            requestHeaderString = URLDecoder.decode(requestHeaderString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return requestHeaderString;
    }

    public static String requestContentString(InputStream inputStream, int contentLength) {
        String requestContentString = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int c;
            int len = 0;
            while ((c = inputStream.read()) != -1) {
                bos.write((char)c);
                len++;
                if (len >= contentLength){
                    break;
                }
            }
            requestContentString = bos.toString();
            requestContentString = URLDecoder.decode(requestContentString);
        } catch (Exception e){
            e.printStackTrace();
        }
        return requestContentString;
    }

    public static Map<String, Object> requestFileContentString(InputStream inputStream, String fileSplitLine) {
        Map<String, Object> paramMap = new HashMap<>();
        try {
            int c;
            StringBuilder sb = new StringBuilder();

            String name = "";
            String filename = "";
            boolean isFile = false;
            long lentgh = 0;

            boolean isDataStart = false;
            while ((c = inputStream.read()) != -1) {
                if (c == '\r'){
                    String line = sb.toString();
                    if ("".equalsIgnoreCase(line)){
                        isDataStart = true;
                        continue;
                    } else {
                        isDataStart = false;
                    }
                    if (line.contains(fileSplitLine)){
                        if (line.endsWith("--")){
                            break;
                        }
                        isFile = false;
                    } else {
                        if (!line.contains(";")){
//                            Content-Type: application/octet-stream
                            String[] lineSplit = line.split(":");
                            String key = lineSplit[0].trim();
                            String value = lineSplit[1].trim();
                            if ("Content-Type".equalsIgnoreCase(key)){
                                if ("application/octet-stream".equalsIgnoreCase(value)){
                                    isFile = true;
                                } else {
                                    isFile = false;
                                }
                            } else if ("Content-Length".equalsIgnoreCase(key)){
                                lentgh = Long.parseLong(value);
                            }
                        } else {
                            //Content-Disposition: form-data; name="logo"; filename="fileA.jpg"
                            String[] lineSplit = line.split(";");
                            String nameStr = lineSplit[1].trim();
                            name = nameStr.substring("name=\"".length(), nameStr.lastIndexOf("\""));
                            if (lineSplit.length >= 3){
                                String filenameStr = lineSplit[2].trim();
                                filename = filenameStr.substring("filename=\"".length(), filenameStr.lastIndexOf("\""));
                            }
                        }
                    }
                    sb.delete(0, sb.length());
                    continue;
                }
                if (c != '\n'){
                    sb.append((char)c);
                } else {
                    if (isDataStart){
                        if (isFile){
                            String parentPath = System.getProperty("user.dir") + File.separator + Config.Server.WEB_ROOT+"/fileTemp";
                            File file = new File(parentPath, filename);
                            if (!file.getParentFile().exists()) {
                                file.getParentFile().mkdirs();
                            }
                            RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
                            if (file.exists() && POSITION != 0){
                                accessFile.seek(POSITION);
                                int tempLen = 0;
                                while ((c = inputStream.read()) != -1) {
                                    tempLen++;
                                    if (tempLen <= POSITION){
                                        continue;
                                    }
                                    accessFile.write(c);
                                    POSITION++;
//                                    LogUtils.info("正在上传"+POSITION+"   "+lentgh);
//                                    if (POSITION % (1024*1024) == 0){  //存1KB存一下
//
//                                    }
                                    if (POSITION >= lentgh) {
                                        //下载完成 归零
                                        POSITION = 0;
                                        accessFile.close();
                                        LogUtils.info("下载完成");
                                        inputStream.read();
                                        inputStream.read();
                                        break;
                                    }
                                }
                                paramMap.put(name, file);

                            } else {
                                accessFile.setLength(lentgh);
                                int tempLen = 0;
                                while ((c = inputStream.read()) != -1) {
                                    tempLen++;
                                    accessFile.write(c);
                                    POSITION++;
//                                  LogUtils.info("正在上传"+POSITION+"   "+lentgh);
//                                    if (POSITION % (1024*1024) == 0){  //存1KB存一下
//
//                                    }
                                    if (tempLen >= lentgh) {
                                        //下载完成 归零
                                        POSITION = 0;
                                        LogUtils.info("下载完成");
                                        accessFile.close();
                                        inputStream.read();
                                        inputStream.read();
                                        break;
                                    }
                                }
                                paramMap.put(name, file);
                            }
                        } else {
                            ByteOutputStream dataOs = new ByteOutputStream();
                            while ((c = inputStream.read()) != -1){
                                if (c == '\r'){
                                    String value = dataOs.toString();
                                    value = URLDecoder.decode(value, Config.Encoding.ENCODE);
                                    paramMap.put(name, value);
                                    inputStream.read();
                                    break;
                                }
                                dataOs.write(c);
                            }
                        }

                        isDataStart = false;
                    }
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return paramMap;
    }
}
